import {dealCache, deepFullCopy, messages} from "share/common";
/**
 * created by zk on 2017/11/22
 */
import React from 'react'
import { connect } from 'react-redux'

import { Button, Table, Badge } from 'antd';
import ResizeTable from 'components/resize-table'
import SearchArea from 'components/search-area.js';
import httpFetch from 'share/httpFetch';
import config from 'config'
import menuRoute from 'routes/menuRoute'
import 'styles/pay-setting/cash-transaction-class/cash-transaction-class.scss'
import {setPaySetting} from "actions/cache";
import configureStore from "stores";

class CashTransactionClass extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      data: [],
      page: 0,
      pageSize: 10,
      columns: [
        {title: messages('pay-setting.key7'/*现金事务类型*/), dataIndex: 'typeName'},  //现金事务类型
        {title: messages('pay-setting.key8'/*现金事务分类代码*/), dataIndex: 'classCode'}, //现金事务代码
        { title: messages('pay-setting.key9'/*现金事物分类名称*/), dataIndex: 'description',
          render: (value, record) => {
            return <span>{record.i18n.description ? record.i18n.description.filter(item => item.language === props.language.code)[0].value : value}</span>
          } },  //现金事务名称
        {title: messages('common.column.status'), dataIndex: 'isEnabled',
          render: isEnabled => (
            <Badge status={isEnabled ? 'success' : 'error'}
                   text={isEnabled ? messages('common.status.enable') : messages('common.status.disable')} />
          )}, //状态
      ],
      pagination: {
        total: 0
      },
      cashTransactionClassDetailPage: menuRoute.getRouteItem('cash-transaction-class-detail','key'),    //组织定义详情的页面项
      newCashTransactionClass:  menuRoute.getRouteItem('new-cash-transaction-class','key'),    //新建现金事务的页面项
      searchParams: {
        setOfBookId: this.props.company.setOfBooksId,
        typeCode: "",
        classCode: "",
        description: "",
      },
      searchForm: [
        {
          type: 'select', id: 'setOfBookId', label: messages('pay-setting.key1'/*账套*/), options: [],
          getUrl: `${config.baseUrl}/api/setOfBooks/by/tenant`,disabled: !this.props.tenantMode,
          labelKey: 'setOfBooksName', valueKey: 'id', method: 'get', defaultValue: this.props.company.setOfBooksName
        },
        {
          type: 'select', id: 'typeCode', label: messages('pay-setting.key7'/*现金事务类型*/), options: [],
          getUrl: `${config.baseUrl}/api/custom/enumerations/template/by/type?type=2104`,
          labelKey: 'messageKey', valueKey: 'value', method: 'get'
        },
        {type: 'input', id: 'classCode', label: messages('pay-setting.key8'/*现金事务分类代码*/) },
        {type: 'input', id: 'description', label: messages('pay-setting.key9'/*现金事物分类名称*/) }
      ],
      nowClass: {},
      showSlideFrame: false
    };
  }

  componentWillMount(){
    let result = this.props.paySetting;
    if(result && JSON.stringify(result) !== "{}"){
      this.dealCache(result);
    } else {
      this.getList();
    }
  }

  dealCache = (result) => {
    let { searchForm, page } = this.state;
    if (result) {
      page = result.page;
      dealCache(searchForm, result);
      this.setState({searchForm, page}, () => {
        this.search(result);
        configureStore.store.dispatch(setPaySetting(null));
      })
    }
  };

  //得到列表数据
  getList(){
    this.setState({ loading: true });
    let params = this.state.searchParams;
    let url = `${config.payUrl}/api/cash/transaction/classes/query?&page=${this.state.page}&size=${this.state.pageSize}`;
    Object.keys(params).map(item => {
      url += params[item] ? `&${item}=${params[item]}` : '';
    });
    return httpFetch.get(url).then((response)=>{
      response.data.map((item)=>{
        item.key = item.id;
      });
      this.setState({
        data: response.data,
        loading: false,
        pagination: {
          total: Number(response.headers['x-total-count']) ? Number(response.headers['x-total-count']) : 0,
          onChange: this.onChangePager,
          current: this.state.page + 1
        }
      })
    });
  }

  //分页点击
  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1
      }, () => {
        this.getList();
      })
  };

  handleRowClick = (record) => {
    const { page } = this.state;
    configureStore.store.dispatch(setPaySetting(Object.assign({},this.props.paySetting,{page})));
    this.context.router.push(this.state.cashTransactionClassDetailPage.url.replace(':classId', record.id));
  };

  search = (result) => {
    let temp = deepFullCopy(result);
    configureStore.store.dispatch(setPaySetting(Object.assign({},temp)));
    this.setState({
      page: 0,
      searchParams: {
        setOfBookId: result.setOfBookId ? (result.setOfBookId === this.props.company.setOfBooksName ? this.props.company.setOfBooksId : result.setOfBookId) : this.props.company.setOfBooksId,
        typeCode: result.typeCode ? result.typeCode : '',
        classCode: result.classCode ? result.classCode : '',
        description: result.description ? result.description : ''
      }
    }, ()=>{
      this.getList();
    })
  };

  clear = () => {
    this.setState({
      searchParams: {
        setOfBookId: this.props.company.setOfBooksId,
        typeCode: "",
        classCode: "",
        description: "",
      }
    },() => {
      this.getList();
    })
  };

  handleNew = () => {
    this.context.router.push(this.state.newCashTransactionClass.url);
  };

  render(){
    const { loading,data, searchForm, pagination, columns } = this.state;
    return(
      <div className="cash-transaction-class">
        <h3 className="header-title">{messages('pay-setting.key12'/*现金事务分类定义*/)}</h3> {/* 现金事务分类定义 */}
        <SearchArea searchForm={searchForm}
                    submitHandle={this.search}
                    isReturnLabel={true}
                    clearHandle={this.clear}/>
        <div className="table-header">
          <div className="table-header-title">{messages('common.total',{total:`${pagination.total}`})}</div>  {/*共搜索到*条数据*/}
          <div className="table-header-buttons">
            <Button type="primary" onClick={this.handleNew}>{messages('common.create')}</Button>  {/*新建*/}
          </div>
        </div>
        <ResizeTable
          dataSource={data}
          loading={loading}
          pagination={pagination}
          columns={columns}
          onRow={record => ({
            onClick: () => this.handleRowClick(record)
          })}
          size="middle"
          bordered/>
      </div>
    )
  }
}

CashTransactionClass.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    paySetting: state.cache.paySetting,
    tenantMode: state.main.tenantMode,
    language: state.main.language
  }
}

export default connect(mapStateToProps)(CashTransactionClass);
